<template>
  <view class="task-detail-page page-content">
    <up-navbar title="任务详情" :autoBack="true" :fixed="true" bgColor="transparent" :border="false" placeholder/>
    
    <view class="detail-container">
      <!-- 任务基本信息 -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">任务信息</text>
          <view class="status-badge" :class="getStatusClass(taskDetail.status)">
            {{ getStatusText(taskDetail.status) }}
          </view>
        </view>
        
        <view class="card-content">
          <view class="info-item">
            <text class="info-label">任务名称：</text>
            <text class="info-value">{{ taskDetail.taskName }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">创建时间：</text>
            <text class="info-value">{{ taskDetail.createTime }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">执行人：</text>
            <text class="info-value">{{ taskDetail.executor }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">核验范围：</text>
            <text class="info-value">{{ getScopeText(taskDetail.verifyScope) }}</text>
          </view>
          <view class="info-item" v-if="taskDetail.description">
            <text class="info-label">任务描述：</text>
            <text class="info-value">{{ taskDetail.description }}</text>
          </view>
        </view>
      </view>
      
      <!-- 进度统计 -->
      <view class="progress-card">
        <view class="card-header">
          <text class="card-title">执行进度</text>
        </view>
        
        <view class="card-content">
          <view class="progress-stats">
            <view class="stat-item">
              <text class="stat-number">{{ taskDetail.totalCount }}</text>
              <text class="stat-label">总车辆数</text>
            </view>
            <view class="stat-item">
              <text class="stat-number completed">{{ taskDetail.completedCount }}</text>
              <text class="stat-label">已完成</text>
            </view>
            <view class="stat-item">
              <text class="stat-number pending">{{ taskDetail.pendingCount }}</text>
              <text class="stat-label">待处理</text>
            </view>
            <view class="stat-item">
              <text class="stat-number unconfirmed">{{ taskDetail.unconfirmedCount }}</text>
              <text class="stat-label">未确认</text>
            </view>
          </view>
          
          <view class="progress-bar">
            <view class="progress-bg">
              <view class="progress-fill" :style="{ width: getProgressWidth() }"></view>
            </view>
            <text class="progress-text">{{ getProgressPercent() }}%</text>
          </view>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-card" v-if="taskDetail.status === 'in_progress'">
        <view class="action-buttons">
          <up-button 
            type="primary" 
            text="查看车辆列表"
            @click="handleViewVehicles"
            :customStyle="{
              flex: 1,
              marginRight: '20rpx',
              height: '80rpx'
            }"
          />
          <up-button 
            type="warning" 
            text="暂停任务"
            @click="handlePauseTask"
            :customStyle="{
              flex: 1,
              height: '80rpx'
            }"
          />
        </view>
      </view>
      
      <!-- 车辆核验列表 -->
      <view class="vehicle-list-card">
        <view class="card-header">
          <text class="card-title">车辆核验记录</text>
          <view class="filter-tabs">
            <view 
              class="filter-tab" 
              :class="{ active: currentFilter === 'all' }"
              @click="handleFilterChange('all')"
            >
              全部
            </view>
            <view 
              class="filter-tab" 
              :class="{ active: currentFilter === 'completed' }"
              @click="handleFilterChange('completed')"
            >
              已完成
            </view>
            <view 
              class="filter-tab" 
              :class="{ active: currentFilter === 'pending' }"
              @click="handleFilterChange('pending')"
            >
              待处理
            </view>
            <view 
              class="filter-tab" 
              :class="{ active: currentFilter === 'unconfirmed' }"
              @click="handleFilterChange('unconfirmed')"
            >
              未确认
            </view>
          </view>
        </view>
        
        <view class="vehicle-list">
          <view class="vehicle-item" v-for="(item, index) in filteredVehicleList" :key="index"
            @click="handleVehicleClick(item)">
            <view class="vehicle-header">
              <text class="vehicle-plate">{{ item.plateNumber }}</text>
              <view class="vehicle-status" :class="getVehicleStatusClass(item.status)">
                {{ getVehicleStatusText(item.status) }}
              </view>
            </view>
            
            <view class="vehicle-content">
              <view class="vehicle-info">
                <text class="info-text">车主：{{ item.ownerName }}</text>
                <text class="info-text">手机：{{ item.phone }}</text>
              </view>
              <view class="vehicle-time">
                <text class="time-text">{{ item.verifyTime || '待核验' }}</text>
              </view>
            </view>
            
            <view class="vehicle-result" v-if="item.result">
              <text class="result-text">核验结果：{{ item.result }}</text>
            </view>
          </view>
        </view>
        
        <view class="empty-state" v-if="filteredVehicleList.length === 0">
          <text class="empty-text">暂无数据</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const taskId = ref('')
const currentFilter = ref('all')

// 任务详情数据
const taskDetail = reactive({
  id: '',
  taskName: '',
  status: 'in_progress',
  createTime: '',
  executor: '',
  verifyScope: 'all',
  description: '',
  totalCount: 0,
  completedCount: 0,
  pendingCount: 0,
  unconfirmedCount: 0
})

// 车辆列表数据
const vehicleList = ref([])

// 页面加载
onLoad((options) => {
  taskId.value = options.id || ''
  loadTaskDetail()
  loadVehicleList()
})

// 加载任务详情
const loadTaskDetail = async () => {
  try {
    // TODO: 调用API获取任务详情
    // const res = await getTaskDetail(taskId.value)
    
    // 模拟数据
    Object.assign(taskDetail, {
      id: taskId.value,
      taskName: '2024年1月场内车辆核验',
      status: 'in_progress',
      createTime: '2024-01-15 09:00:00',
      executor: '张三',
      verifyScope: 'all',
      description: '对场内所有车辆进行核验，确保车辆信息准确性',
      totalCount: 150,
      completedCount: 120,
      pendingCount: 25,
      unconfirmedCount: 5
    })
  } catch (error) {
    console.error('加载任务详情失败:', error)
  }
}

// 加载车辆列表
const loadVehicleList = async () => {
  try {
    // TODO: 调用API获取车辆列表
    // const res = await getTaskVehicleList(taskId.value)
    
    // 模拟数据
    vehicleList.value = [
      {
        id: 1,
        plateNumber: '京A12345',
        ownerName: '张三',
        phone: '138****1234',
        status: 'completed',
        verifyTime: '2024-01-15 10:30:00',
        result: '核验通过'
      },
      {
        id: 2,
        plateNumber: '京B67890',
        ownerName: '李四',
        phone: '139****5678',
        status: 'pending',
        verifyTime: '',
        result: ''
      },
      {
        id: 3,
        plateNumber: '京C11111',
        ownerName: '王五',
        phone: '136****9999',
        status: 'unconfirmed',
        verifyTime: '2024-01-15 11:00:00',
        result: '待确认'
      }
    ]
  } catch (error) {
    console.error('加载车辆列表失败:', error)
  }
}

// 过滤后的车辆列表
const filteredVehicleList = computed(() => {
  if (currentFilter.value === 'all') {
    return vehicleList.value
  }
  return vehicleList.value.filter(item => item.status === currentFilter.value)
})

// 获取状态样式类
const getStatusClass = (status: string) => {
  const statusMap = {
    'pending': 'status-pending',
    'in_progress': 'status-progress',
    'completed': 'status-completed',
    'paused': 'status-paused'
  }
  return statusMap[status] || 'status-pending'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    'pending': '待开始',
    'in_progress': '进行中',
    'completed': '已完成',
    'paused': '已暂停'
  }
  return statusMap[status] || '未知'
}

// 获取范围文本
const getScopeText = (scope: string) => {
  const scopeMap = {
    'all': '全部场内车辆',
    'area': '指定区域车辆',
    'custom': '自定义车辆列表'
  }
  return scopeMap[scope] || '未知'
}

// 获取进度宽度
const getProgressWidth = () => {
  const percent = (taskDetail.completedCount / taskDetail.totalCount) * 100
  return `${Math.min(percent, 100)}%`
}

// 获取进度百分比
const getProgressPercent = () => {
  const percent = (taskDetail.completedCount / taskDetail.totalCount) * 100
  return Math.round(Math.min(percent, 100))
}

// 获取车辆状态样式类
const getVehicleStatusClass = (status: string) => {
  const statusMap = {
    'completed': 'vehicle-status-completed',
    'pending': 'vehicle-status-pending',
    'unconfirmed': 'vehicle-status-unconfirmed'
  }
  return statusMap[status] || 'vehicle-status-pending'
}

// 获取车辆状态文本
const getVehicleStatusText = (status: string) => {
  const statusMap = {
    'completed': '已完成',
    'pending': '待处理',
    'unconfirmed': '未确认'
  }
  return statusMap[status] || '未知'
}

// 筛选变化
const handleFilterChange = (filter: string) => {
  currentFilter.value = filter
}

// 查看车辆列表
const handleViewVehicles = () => {
  uni.navigateTo({
    url: `/pages/vehicle-internal-verify/vehicle-list?taskId=${taskId.value}`
  })
}

// 暂停任务
const handlePauseTask = () => {
  uni.showModal({
    title: '确认暂停',
    content: '确定要暂停当前任务吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用API暂停任务
          // await pauseTask(taskId.value)
          uni.showToast({
            title: '任务已暂停',
            icon: 'success'
          })
          taskDetail.status = 'paused'
        } catch (error) {
          console.error('暂停任务失败:', error)
          uni.showToast({
            title: '暂停失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

// 车辆点击
const handleVehicleClick = (item: any) => {
  uni.navigateTo({
    url: `/pages/vehicle-internal-verify/vehicle-detail?taskId=${taskId.value}&vehicleId=${item.id}`
  })
}

// 返回首页
const handleBackToIndex = () => {
  uni.redirectTo({
    url: '/pages/vehicle-internal-verify/index'
  })
}
</script>

<style lang="scss" scoped>
.task-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.detail-container {
  padding: 20rpx;
}

.info-card,
.progress-card,
.action-card,
.vehicle-list-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  padding: 30rpx 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
  
  &.status-pending {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  &.status-progress {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  &.status-completed {
    background-color: #f6ffed;
    color: #52c41a;
  }
  
  &.status-paused {
    background-color: #fff1f0;
    color: #ff4d4f;
  }
}

.card-content {
  padding: 20rpx 30rpx 30rpx;
}

.info-item {
  display: flex;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 28rpx;
  color: #666666;
  min-width: 160rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
}

.progress-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30rpx;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8rpx;
  
  &.completed {
    color: #52c41a;
  }
  
  &.pending {
    color: #fa8c16;
  }
  
  &.unconfirmed {
    color: #ff4d4f;
  }
}

.stat-label {
  font-size: 24rpx;
  color: #666666;
}

.progress-bar {
  display: flex;
  align-items: center;
}

.progress-bg {
  flex: 1;
  height: 12rpx;
  background-color: #f0f0f0;
  border-radius: 6rpx;
  overflow: hidden;
  margin-right: 16rpx;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 6rpx;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 28rpx;
  color: #333333;
  font-weight: 600;
  min-width: 80rpx;
}

.action-buttons {
  display: flex;
  padding: 30rpx;
}

.filter-tabs {
  display: flex;
  gap: 20rpx;
}

.filter-tab {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #666666;
  background-color: #f5f5f5;
  transition: all 0.3s ease;
  
  &.active {
    background-color: #1890ff;
    color: #ffffff;
  }
}

.vehicle-list {
  padding: 0 30rpx 30rpx;
}

.vehicle-item {
  border-bottom: 1rpx solid #f0f0f0;
  padding: 24rpx 0;
  
  &:last-child {
    border-bottom: none;
  }
}

.vehicle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.vehicle-plate {
  font-size: 30rpx;
  font-weight: 600;
  color: #333333;
}

.vehicle-status {
  padding: 6rpx 12rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
  
  &.vehicle-status-completed {
    background-color: #f6ffed;
    color: #52c41a;
  }
  
  &.vehicle-status-pending {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  &.vehicle-status-unconfirmed {
    background-color: #fff1f0;
    color: #ff4d4f;
  }
}

.vehicle-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.vehicle-info {
  flex: 1;
}

.info-text {
  display: block;
  font-size: 26rpx;
  color: #666666;
  margin-bottom: 8rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.vehicle-time {
  text-align: right;
}

.time-text {
  font-size: 24rpx;
  color: #999999;
}

.vehicle-result {
  margin-top: 12rpx;
}

.result-text {
  font-size: 26rpx;
  color: #1890ff;
}

.empty-state {
  text-align: center;
  padding: 60rpx 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}
</style>